package edu.cicese.tm;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.Container;
import java.awt.Image;
import java.awt.Insets;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 15/03/11
 * Time: 08:24 PM
 */
public class SwingUtil {

	//! Gets a scaled image with the same aspect ratio
	public static Image getScaledImage(Image originalImage, int width, int height) {
		double originalHeight = originalImage.getHeight(null);
		double originalWidth = originalImage.getWidth(null);
		double heightScale = height / originalHeight;
		double widthScale = width / originalWidth;
		double scale = heightScale < widthScale ? heightScale : widthScale;
		int newHeight = (int) (originalHeight * scale);
		int newWidth = (int) (originalWidth * scale);
		return originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_FAST);
//		return originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
	}

	//! Adds a JButton
	public static void addButton(JButton button, int x, int y, int width, int height,
	                              String toolTipText, Icon icon, Icon rIcon, Icon pIcon,
	                              JPanel pane, Container container) {
		button.setToolTipText(toolTipText);
		button.setBounds(x, y, width, height);
		button.setIcon(icon);
		button.setRolloverIcon(rIcon);
		button.setPressedIcon(pIcon);
		button.setContentAreaFilled(false);
		button.setBorder(new EmptyBorder(0, 0, 0, 0));
		button.setMargin(new Insets(0, 0, 0, 0));
		if (pane == null) {
			container.add(button);
		}
		else {
			pane.add(button);
		}
	}

	//! Adds a JCheckBox
	public static void addCheckBox(JCheckBox box, int x, int y, int width, int height,
	                                JPanel pane, Container container) {
		box.setBounds(x, y, width, height);
	    box.setBackground(Color.WHITE);
		if (pane == null) {
			container.add(box);
		}
		else {
			pane.add(box);
		}
	}

	//! Adds a JRadioButton
	public static void addRadioButton(JRadioButton button, int x, int y, int width,
	                                  int height, String text, JPanel pane) {
		button.setBounds(x, y, width, height);
		button.setText(text);
		button.setBackground(Color.WHITE);
		pane.add(button);
	}

	//! Adds a JLabel
	public static void addLabel(JLabel label, int x, int y, int width, int height,
	                            String text, JPanel pane, Container container) {
		label.setBounds(x, y, width, height);
		label.setText(text);
		if (pane == null) {
			container.add(label);
		}
		else {
			pane.add(label);
		}
	}
}
